﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 随机平台主题
/// </summary>
public class PlatformSprite : MonoBehaviour
{
    public SpriteRenderer[] spriteRenderers;
    //随机障碍物
    public GameObject obstacle;
    private bool startTimer;//是否开始计时
    private float fallTime;//掉落时间从platformSpawner获得
    private Rigidbody2D my_body;

    private void Awake()
    {
        my_body = GetComponent<Rigidbody2D>();
    }

    public void Init(Sprite sprite,float fallTime,int obstacleDir)
    {
        my_body.bodyType = RigidbodyType2D.Static;//生成静态图
        this.fallTime = fallTime;//赋值
        startTimer = true;//开始计时
        for (int i = 0; i < spriteRenderers.Length; i++)
        {
            spriteRenderers[i].sprite = sprite;
        }
        if (obstacleDir==0)//朝右边
        {
            if (obstacle != null)
            {
                //重新构造障碍物-相反
                obstacle.transform.localPosition = new Vector3(
                    -obstacle.transform.localPosition.x,
                    obstacle.transform.localPosition.y,0
                    );
            }
        }
    }
    private void Update()
    {
        if (GameManager.Instance.IsGameStarted == false|| 
            GameManager.Instance.PlayerIsMove==false) return;
        
        if (startTimer)
        {
            fallTime -= Time.deltaTime;
            if (fallTime<0)
            {
                //计时结束，掉落  将RigidBody设置成动态的
                startTimer = false;
                if (my_body.bodyType!=RigidbodyType2D.Dynamic)
                {
                    my_body.bodyType = RigidbodyType2D.Dynamic;//下落  隐藏物体
                    StartCoroutine(DealyHide());//开启携程 
                }
            }
        }
        if (transform.position.y-Camera.main.transform.position.y<-6)
        {
            StartCoroutine(DealyHide());
        }
    }
    /// <summary>
    /// 隐藏平台
    /// </summary>
    /// <returns></returns>
    private IEnumerator DealyHide()
    {
        yield return new WaitForSeconds(1f);
        gameObject.SetActive(false);
    }
}
